const timerS = require('./src/s/timerS');
const redisClient = require('./util/cache');
const config = require(`./config/${process.env.CONFIG}`);
const logger = require('./util/logInit.js').createLogger("server");
//防止定时任务挂掉了，重启时定时任务都失效了
const __init = async () =>{
    //不支持nginx负载均衡
    //获取当前进程数量
    // let process_num = process.env.instances || 1;
    //pm2的自增变量是从0开始, 可以根据id判断从而启动一个或者多个
    let process_id = process.env.NODE_APP_INSTANCE || 0;
    logger.info(`[init]第[${parseInt(process_id) + 1}]个进程启动：进程ID：${process.env.pm_id}`);
    //根据pm2自增变量查询对于的redis重启对应的定时任务
    let result = await redisClient.hgetallAsync(config.redis_key+"_"+process_id);
    if(result !== null){
        for (const k in result) {
            let v = JSON.parse(result[k]);
            logger.info(`[init][${k}]任务重启`)
            logger.info(`[init][${k}]重启参数：${JSON.stringify(v)}`)
            let r = await timerS.set(k,v);
            logger.info(`[init][${k}]重启结果：${JSON.stringify(r)}`)
        }
    }
    //每一个进程进行消息订阅，关闭定时任务时则可以判断是否存在这个全局变量而选择是否关闭
    __subscribe();
}

//多进程模式下通过订阅控制定时器关闭
//redis、消费、订阅使用
const redisClient2 = require('./util/cache2');
const __subscribe = async () =>{
    logger.info(`构造消息订阅频道：[${config.timer_close_name}]`)
    redisClient2.subscribeAsync(config.timer_close_name);
}
//处理订阅
redisClient2.on('message',async function(err,response){
    response = response.toString();
    let pm2_id = process.env.pm_id;
    let param = JSON.parse(response);
    logger.info(`[${pm2_id}][${param.uuid}][${config.timer_close_name}]接收订阅消息：${response}`)
    logger.info(`[${pm2_id}][${param.uuid}]线程关闭[${param.id}}]定时任务。`)
    try {
        let result = await timerS.cancel(param.uuid,param);
        logger.info(`[${pm2_id}][${param.uuid}]线程关闭[${param.id}}]成功：${JSON.stringify(result)}。`)
    } catch (error) {
        logger.info(`[${pm2_id}][${param.uuid}]线程关闭[${param.id}}]失败：${error.message}。`)
    }
});
//redis挂了重新订阅
redisClient2.on("error", function (err) {
    __subscribe();
});


module.exports = {
    __init:__init
};